#!/bin/bash
# 华为云 OBS 备份检查脚本（HTML 邮件版）- 检查当天备份目录并列出文件

# 配置部分
BUCKET_NAME="y***-dba-backup"
IP_DIRS=("192.168.10.24" "192.168.1.21")  # 固定的两个IP目录
EMAIL_TO="user@163.com"
EMAIL_FROM="backup-monitor@$(hostname)"
EMAIL_REPLY_TO="noreply@$(hostname)"
LOG_FILE="/var/log/obs_backup_check.log"
TODAY=$(date +%Y%m%d)  # 格式如：20250513
START_TIME=$(date +%s)
OBSUTIL_BIN="/usr/local/bin/obsutil/stable/obsutil"

# 初始化日志
init_log() {
    echo "==============================================" >> "$LOG_FILE"
    echo "OBS 备份检查开始于: $(date +'%Y-%m-%d %H:%M:%S')" >> "$LOG_FILE"
    echo "检查日期: ${TODAY}" >> "$LOG_FILE"
    echo "----------------------------------------------" >> "$LOG_FILE"
}

# 记录日志
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# 发送邮件
send_email() {
    local subject=$1
    local html_body=$2

    {
        echo "From: $EMAIL_FROM"
        echo "To: $EMAIL_TO"
        echo "Reply-To: $EMAIL_REPLY_TO"
        echo "Subject: $subject"
        echo "MIME-Version: 1.0"
        echo "Content-Type: text/html; charset=UTF-8"
        echo "X-Mailer: OBS Backup Monitor/1.0"
        echo ""
        echo "$html_body"
    } | sendmail -t -f "$EMAIL_FROM"

    if [ $? -eq 0 ]; then
        log "HTML 邮件已成功发送至 $EMAIL_TO"
    else
        log "错误：邮件发送失败"
    fi
}

# 检查单个IP目录并生成文件列表
check_ip_directory() {
    local ip_dir=$1
    local check_date=${TODAY}
    local today_dir="obs://${BUCKET_NAME}/${ip_dir}/${check_date}/"
    local output=""

    log "检查IP目录: ${ip_dir}"

    # 检查目录是否存在
    if ! $OBSUTIL_BIN ls "$today_dir" >/dev/null 2>&1; then
        log "警告：目录 ${today_dir} 不存在"
        output="<div style='margin-bottom:20px;'>"
        output+="<h3 style='color:red;font-size:16px;'>IP: ${ip_dir} - ${check_date}</h3>"
        output+="<p style='color:red;font-size:14px;'>❌ 目录不存在或无法访问</p>"
        output+="</div>"
        echo "$output"
        return 1
    fi

    # 获取文件列表
    files=$($OBSUTIL_BIN ls "$today_dir" 2>/dev/null | grep -E "^obs://.*[^/]$" | awk '{print $1}')
    
    if [ -z "$files" ]; then
        log "警告：目录 ${today_dir} 为空"
        output="<div style='margin-bottom:20px;'>"
        output+="<h3 style='color:red;font-size:16px;'>IP: ${ip_dir} - ${check_date}</h3>"
        output+="<p style='color:red;font-size:14px;'>❌ 目录为空</p>"
        output+="</div>"
        echo "$output"
        return 1
    fi

    # 生成文件列表表格
    output="<div style='margin-bottom:20px;'>"
    output+="<h3 style='font-size:16px;'>IP: ${ip_dir} - ${check_date}</h3>"
    output+="<table border='1' cellspacing='0' cellpadding='6' style='border-collapse:collapse;font-size:14px;'>"
    output+="<tr style='background-color:#f0f0f0;'><th>文件名</th></tr>"
    
    for file in $files; do
        filename=$(basename "$file")
        output+="<tr><td>${filename}</td></tr>"
    done

    output+="</table>"
    output+="<p style='font-size:14px;'>文件数: $(echo "$files" | wc -l)</p>"
    output+="</div>"
    
    echo "$output"
    return 0
}

# 检查 OBS 备份
check_obs_backup() {
    log "开始检查 OBS 桶 ${BUCKET_NAME} 中的备份..."

    # 检查 obsutil 是否存在
    if [ ! -x "$OBSUTIL_BIN" ]; then
        log "错误：obsutil 不存在或不可执行: $OBSUTIL_BIN"
        send_email "❌ [紧急] ${TODAY} OBS 检查失败" "<p style='font-size:16px;'>obsutil 工具不存在或不可执行</p>"
        exit 1
    fi

    has_error=0
    file_tables=""

    # 检查每个IP目录
    for ip_dir in "${IP_DIRS[@]}"; do
        result=$(check_ip_directory "$ip_dir")
        status=$?
        
        file_tables+="$result"
        
        if [ $status -ne 0 ]; then
            has_error=1
        fi
    done

    # 构建邮件内容
    date_info="<p style='font-size:16px;'>检查日期: <b>${TODAY}</b></p>"
    bucket_info="<p style='font-size:16px;'>桶名: <b>${BUCKET_NAME}</b></p>"
    
    # 根据检查结果设置邮件主题和标题
    if [ $has_error -eq 1 ]; then
        subject="❌ [紧急] ${TODAY} OBS备份检查失败"
        title="<h2 style='color:red;font-size:18px;'>OBS备份检查失败</h2>"
    else
        subject="✅ [正常] ${TODAY} OBS备份检查正常"
        title="<h2 style='color:green;font-size:18px;'>OBS备份检查正常</h2>"
    fi

    message="${title}"
    message+="${bucket_info}"
    message+="${date_info}"
    message+="${file_tables}"

    # 添加执行时间信息
    END_TIME=$(date +%s)
    DURATION=$((END_TIME - START_TIME))
    message+="<p style='color:#666;font-size:14px;'>脚本执行耗时: ${DURATION}秒</p>"

    full_html="<html><body style='font-family:Arial,sans-serif;font-size:14px;'>${message}<p style='color:#888;font-size:12px;'>由自动备份监控系统生成。</p></body></html>"

    send_email "$subject" "$full_html"
}

# 主程序
init_log
check_obs_backup
echo "OBS 备份检查完成于: $(date +'%Y-%m-%d %H:%M:%S')" >> "$LOG_FILE"
echo "==============================================" >> "$LOG_FILE"